<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>数据管理</el-breadcrumb-item>
      <el-breadcrumb-item>地形数据</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="filterName" @input="inputAlter" placeholder="地形名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">
          搜索
        </el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleUpload()">
          上传数据集
        </el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="
        dataList.slice(
          (this.pageparm.currentPage - 1) * this.pageparm.pageSize,
          this.pageparm.currentPage * this.pageparm.pageSize
        )
      " highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%">
      <el-table-column sortable prop="name" label="数据名称"> </el-table-column>
      <el-table-column sortable prop="type" label="数据类型" :formatter="formatterType"> </el-table-column>
      <el-table-column sortable prop="id" label="数据集ID"> </el-table-column>
      <el-table-column sortable prop="url" label="服务地址"> </el-table-column>
      <el-table-column sortable prop="updated_at" label="更新时间">
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <!-- <el-button size="mini" @click="rsPublish(scope.row)">
            服务发布
          </el-button> -->
          <el-button size="mini" @click="uploadTerrainTiles(scope.row)">
            服务上传
          </el-button>
          <el-button size="mini" type="danger" @click="deleteRow(scope.$index, scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 数据集上传对话框 -->
    <el-dialog title="上传数据集" :visible.sync="uploadDialogVisible" width="30%" @close="closeUploadDialog">
      <div class="container">
        <el-upload class="upload" drag :action="uploadUrl" :headers="headers" :before-upload="beforeUpload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将DEM数据拖到此处，或<em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            只能上传TIF格式数据，支持WGS84/CGCS2000地理坐标系
          </div>
        </el-upload>
      </div>
    </el-dialog>
    <!-- 编辑界面 -->
    <el-dialog title="编辑地形信息" :visible.sync="editDialogVisible" width="30%" @close="closeEditDialog">
      <el-form label-width="120px" :model="editRow" ref="editRow">
        <el-form-item label="数据名称">
          <el-input size="small" v-model="editRow.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="数据类型">
          <el-select placeholder="请选类型" v-model="editRow.type" style="display: block" value-key="id">
            <el-option v-for="t in types" :label="t.name" :key="t.type" :value="t.type">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitEdit('editRow')">
          保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 服务集上传对话框 -->
    <el-dialog title="上传服务集" :visible.sync="uploadTilesVisible" width="30%" @close="closeTilesDialog">
      <div class="container">
        <el-upload class="upload" drag :action="upTilesUrl" :headers="headers" :before-upload="beforeTilesUpload"
          :on-success="afterTilesUpload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将地形瓦片包拖到此处，或<em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">
            只能上传瓦片zip包数据，支持.terrain规格地形服务
          </div>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from "../../components/Pagination";

  export default {
    data() {
      return {
        loading: false, //是显示加载
        uploadDialogVisible: false,
        editDialogVisible: false, //控制编辑页面显示与隐藏
        uploadTilesVisible: false,
        filterName: "", //搜索框内容
        uploadUrl: cfg.baseURL + "/terrains/upload/",
        upTilesUrl: cfg.baseURL + "/terrains/x/upload/",
        headers: {
          Authorization: "Bearer " + localStorage.getItem("token"),
        },
        types: [
          {
            name: "地形",
            type: "terrain",
          },
          {
            name: "其他",
            type: "others",
          },
        ],

        editRow: {
          id: "",
          name: "",
          type: "",
        },
        // rules表单验证
        rules: {
          id: [{ required: true, message: "数据集id不能为空", trigger: "blur" }],
          name: [{ required: true, message: "请输入地形名称", trigger: "blur" }],
        },
        dataList: [], //用户数据
        // 分页参数
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10,
        },
        thumbnail:
          "",
      };
    },
    // 注册组件
    components: {
      Pagination,
    },
    /**
     * 创建完毕
     */
    created() {
      // 获取数据列表
      this.getDataList();
    },
    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      // 获取影像列表
      getDataList() {
        this.$axios.get("/terrains/").then((res) => {
          this.dataList = res.data.results.list;
          this.pageparm.total = res.data.results.total;
        });
      },
      // 分页插件事件
      callFather(parm) {
        this.pageparm.currentPage = parm.currentPage;
        this.pageparm.pageSize = parm.pageSize;
      },
      handleUpload() {
        this.uploadDialogVisible = true;
      },
      beforeUpload(file) {
        let lext = file.name.substr(file.name.lastIndexOf(".")).toLowerCase();
        const isTIF = lext === ".tif";

        if (!isTIF) {
          this.$message.error("上传数据只能 .tif 格式!");
        }

        return isTIF;
      },
      //显示编辑界面
      handleEdit: function (index, row) {
        this.editDialogVisible = true;
        this.editRow.id = row.id;
        this.editRow.name = row.name;
        this.editRow.type = row.type;
      },
      // 编辑、增加页面保存方法
      submitEdit(editData) {
        this.$refs[editData].validate((valid) => {
          if (valid) {
            this.loading = true;
            this.$axios
              .post("/terrains/info/" + this.editRow.id + "/", {
                name: this.editRow.name,
                type: this.editRow.type,
              })
              .then((res) => {
                this.editDialogVisible = false;
                this.loading = false;
                this.getDataList();
              })
              .catch((err) => {
                this.editDialogVisible = false;
                this.loading = false;
                this.$message.error("编辑数据提交失败，请稍后再试！");
              });
          }
        });
      },
      // 删除
      deleteRow(index, row) {
        this.$confirm("确定要删除吗?", "信息", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then((res) => {
            this.$axios.post("/terrains/delete/" + row.id + "/").then((res) => {
              this.getDataList();
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      },
      // 服务发布
      uploadTerrainTiles(row) {
        this.upTilesUrl += row.id + "/";
        this.uploadTilesVisible = true;
      },
      beforeTilesUpload(file) {

        let lext = file.name.substr(file.name.lastIndexOf(".")).toLowerCase();
        const isZIP = lext === ".zip";

        if (!isZIP) {
          this.$message.error("上传数据只能 .zip 格式!");
        }

        return isZIP;
      },
      afterTilesUpload(res, file) {
        this.$axios
          .post("/terrains/info/" + res.results.id + "/", {
            thumbnail: this.thumbnail,
          })
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            this.$message.error("更新默认缩略图失败，请稍后再试！");
          });
      },
      // 服务发布
      publishTerainTiles(row) {
        console.log(row);
        this.$axios.post("/terrains/publish/" + row.id + "/").then((res) => {
          console.log(res);
          this.$axios
            .post("/terrains/info/" + row.id + "/", {
              thumbnail: this.thumbnail,
            })
            .then((res) => {
              console.log(res);
            })
            .catch((err) => {
              this.$message.error("更新默认缩略图失败，请稍后再试！");
            });
        });
      },
      // 输入框内容改变
      inputAlter() {
        if (this.filterName == "") {
          this.getDataList();
        } else {
          this.dataList = this.dataList.filter((value) => {
            return value.name.match(this.filterName);
          });
          this.pageparm.total = this.dataList.length;
        }
      },
      // 搜索事件
      search() {
        this.dataList = this.dataList.filter((value) => {
          return value.name.match(this.filterName);
        });
        this.pageparm.total = this.dataList.length;
      },
      closeUploadDialog() {
        this.uploadDialogVisible = false;
        this.getDataList();
      },
      // 关闭编辑、增加弹出框
      closeEditDialog() {
        this.editDialogVisible = false;
      },
      closeTilesDialog() {
        this.uploadTilesVisible = false;
        this.getDataList();
      },
      formatterType(row) {
        const ty = this.types.find(obj => obj.type == row.type);
        return ty ? ty.name : row.type;
      }
    },
  };
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }

  .userRole {
    width: 100%;
  }

  .el-upload-list--picture .el-upload-list__item-thumbnail {
    display: none !important;
  }

  .container {
    width: 100%;
    display: flex;
    justify-content: center;
  }

  .upload {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
</style>